<template lang="pug">
  div(ref="decoratePagination").h-100
    resize-sensor(@resize="resizeHandler", :initial='true')
    div(:style="{height: tableHeight + 'px',overflow: 'auto'}")
      slot(:filtered-data="showData" :table-height="tableHeight"  v-if="tableHeightChangeFlag && tableHeight")
      //slot(:filtered-data="showData" :table-height="tableHeight"  v-if = "!tableHeightChangeFlag && tableHeight")
    div(ref="pagination" style="display:inline-block;width:100%;" :class="{'pagination-transparent': paginationTheme==='transparent','pagination-black': paginationTheme==='black'}").mt-3.clearfix
      table(style="width:100%")
        tr
          td(align="center")
            el-pagination(:class="{'float-right': ['transparent', 'black'].indexOf(paginationTheme) === -1}" ref='elPagination' v-if='paginationChangeFlag' :total="totalData" :layout="layout"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :current-page="currentPage"
            @current-change="handleCurrentPageChange"
            @size-change="handlePageSizeChange").fr
            el-pagination(:class="{'float-right': ['transparent', 'black'].indexOf(paginationTheme) === -1}" ref='elPagination' v-else :total="totalData" :layout="layout"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :current-page="currentPage"
            @current-change="handleCurrentPageChange"
            @size-change="handlePageSizeChange").fr
</template>

<script>
import _ from 'lodash'
import ResizeSensor from '../resizeSensor/resizeSensor'

export default {
  name: 'decoratePagination',
  components: { ResizeSensor },
  props: {
    listKey: {
      default: 'list'
    },
    totalKey: {
      default: 'total'
    },
    data: {},
    isAsync: {},
    asyncMethod: {},
    page: {},
    pageSize: {},
    paginationTheme: String,
    layout: {
      default: 'total, sizes, prev, pager, next'
    }
  },
  data() {
    return {
      paginationChangeFlag: true,
      currentPageSize: this.pageSize || 10,
      currentPage: 1,
      showData: [],
      totalData: null,
      tableHeight: 0,
      tableHeightChangeFlag: false
    }
  },
  watch: {
    data(newValue, oldValue) {
      // 前端分页展示数据
      if (!this.isAsync) {
        this.showDataOfPage()
      }
    }
  },
  mounted() {
    // 获取组件父元素
    let parentContainer = this.$refs.decoratePagination.parentNode

    // 计算组件父元素高度
    this.setHeight = () => {
      let parentContainerHeight = parentContainer.offsetHeight
      // 父组件销毁子组件未销毁的情况会有空指针异常
      if (!this.$refs.pagination) {
        return
      }
      // 表格的高度 = 父组件的高度 - page分页组件的高度

      this.tableHeight = parentContainerHeight - this.$refs.pagination.scrollHeight - 16
      this.tableHeightChangeFlag = false
      this.$nextTick(() => {
        this.tableHeightChangeFlag = true
      })
      // this.tableHeightChangeFlag = !this.tableHeightChangeFlag
    }
    this.setHeightDebounce = _.debounce(this.setHeight, 250)

    if (this.isAsync) {
      this.asyncMethod(this.pageSize || this.currentPageSize, this.page || this.currentPage).then(data => {
        this.showData = data[this.listKey]
        this.totalData = data[this.totalKey]
      })
    } else {
      this.showDataOfPage()
    }
  },
  methods: {
    refresh(type) {
      if (!this.isAsync) {
        this.showDataOfPage()
      } else {
        // 搜索时从第一页开始
        if (type && this.currentPage > 1) {
          this.paginationChangeFlag = !this.paginationChangeFlag
          this.currentPage = 1
          // this.$refs.elPagination.handleCurrentChange(1)
        }
        this.asyncMethod(this.currentPageSize, this.currentPage, true).then(data => {
          this.showData = data[this.listKey]
          this.totalData = data[this.totalKey]
        })
      }
    },
    changePage(number) {
      this.$refs.elPagination.handleCurrentChange(number)
    },
    resizeHandler() {
      if (this.$refs.decoratePagination) {
        this.setHeightDebounce()
      }
    },
    showDataOfPage() {
      let startIndex = this.currentPageSize * (this.currentPage - 1)
      let endIndex = this.currentPageSize * this.currentPage
      // 根据page、pageSize筛选展示的数据
      this.showData = this.data.slice(startIndex, endIndex)
      if (!this.showData.length && this.currentPage > 1) {
        this.currentPage--
        this.showDataOfPage()
      }
      this.totalData = this.data.length
      this.$emit('pageChange', this.data.slice(startIndex, endIndex))
    },
    handleCurrentPageChange(page) {
      this.currentPage = page

      // page变化时，分页展示的数据也随之变化
      if (!this.isAsync) {
        this.showDataOfPage()
      } else {
        this.asyncMethod(this.currentPageSize, this.currentPage).then(data => {
          this.showData = data[this.listKey]
          this.totalData = data[this.totalKey]
        })
      }
    },
    handlePageSizeChange(pageSize) {
      this.currentPageSize = pageSize

      // pageSize变化时，分页展示的数据也随之变化
      if (!this.isAsync) {
        this.showDataOfPage()
      } else {
        this.asyncMethod(this.currentPageSize, this.currentPage).then(data => {
          this.showData = data[this.listKey]
          this.totalData = data[this.totalKey]
        })
      }
    }
  }
}
</script>

<style lang="scss">
  .pagination-black{
    * {
      background: transparent !important;
      color: #000 !important;
    }
    .el-pager li.active {
      color: #679ef0 !important;
    }
  }
  .pagination-transparent {
    * {
      background: transparent !important;
      color: #cccccc !important;
    }
    .el-pager li.active {
      color: #679ef0 !important;
    }
  }
</style>
